<template>
  <div class="article-list" ref="articleList">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <article-item
          v-for="article in list"
          :key="article.id"
          :article="article"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { throttle } from "lodash";
import { getArticles } from "@/api/article";
import ArticleItem from "./article-item.vue";
export default {
  name: "ArticleList",
  components: {
    ArticleItem,
  },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      timestamp: null,
      refreshing: false,
    };
  },
  methods: {
    async onLoad() {
      try {
        const res = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1,
        });
        //模拟出错
        // if (Math.random() > 0.7) {
        //   JSON.parse('abc')
        // }
        this.list.push(...res.data.results);
        this.loading = false;
        if (res.data.pre_timestamp) {
          this.timestamp = res.data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (error) {
        this.error = true;
        this.loading = false;
      }
    },
    onRefresh() {
      // 清空列表数据
      this.list = [];
      this.finished = false;
      this.timestamp = null;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
      this.refreshing = false;
    },
  },
  mounted() {
    this.$refs.articleList.addEventListener(
      "scroll",
      throttle(function () {
        this.setAttribute("scroll_top", this.scrollTop);
      }, 200)
    );
  },
  activated () {
    const scrollTop = this.$refs.articleList.getAttribute('scroll_top')
    this.$refs.articleList.scrollTop = scrollTop
  }
};
</script>
<style lang="less" scoped>
.article-list {
  overflow: auto;
  height: calc(100vh - 188px);
}
</style>